package com.zyf.lj.util;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import io.jsonwebtoken.security.Keys;
import org.springframework.stereotype.Component;

import javax.crypto.SecretKey;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * JWT工具类
 */
@Component
public class JwtUtil {

    // 密钥
    private static final String SECRET_KEY = "shandong_labor_vocational_college_secret_key_2025_secure_jwt_token";
    
    // 使用固定密钥
    private static final SecretKey KEY = Keys.hmacShaKeyFor(
            SECRET_KEY.getBytes(StandardCharsets.UTF_8)
    );
    
    // 过期时间（毫秒）- 24小时
    private static final long EXPIRATION_TIME = 86400000;
    
    /**
     * 生成JWT令牌
     * @param userId 用户ID
     * @param openid 微信openid
     * @return JWT令牌
     */
    public String generateToken(Long userId, String openid) {
        Map<String, Object> claims = new HashMap<>();
        claims.put("userId", userId);
        
        // 处理openid，避免非法Base64字符
        String safeOpenid = openid;
        if (openid != null && !openid.isEmpty()) {
            // 使用Base64对openid进行编码，确保安全
            safeOpenid = Base64.getEncoder().encodeToString(openid.getBytes());
        }
        claims.put("openid", safeOpenid);
        
        return Jwts.builder()
                .setClaims(claims)
                .setIssuedAt(new Date())
                .setExpiration(new Date(System.currentTimeMillis() + EXPIRATION_TIME))
                .signWith(KEY)
                .compact();
    }
    
    /**
     * 验证JWT令牌
     * @param token JWT令牌
     * @return 是否有效
     */
    public boolean validateToken(String token) {
        try {
            Jwts.parserBuilder()
                .setSigningKey(KEY)
                .build()
                .parseClaimsJws(token);
            return true;
        } catch (Exception e) {
            return false;
        }
    }
    
    /**
     * 从JWT令牌中获取用户ID
     * @param token JWT令牌
     * @return 用户ID
     */
    public Long getUserIdFromToken(String token) {
        Claims claims = Jwts.parserBuilder()
                .setSigningKey(KEY)
                .build()
                .parseClaimsJws(token)
                .getBody();
        
        return Long.valueOf(claims.get("userId").toString());
    }
    
    /**
     * 从JWT令牌中获取微信openid
     * @param token JWT令牌
     * @return 微信openid
     */
    public String getOpenidFromToken(String token) {
        Claims claims = Jwts.parserBuilder()
                .setSigningKey(KEY)
                .build()
                .parseClaimsJws(token)
                .getBody();
        
        String encodedOpenid = claims.get("openid").toString();
        // 解码Base64编码的openid
        return new String(Base64.getDecoder().decode(encodedOpenid));
    }
} 